import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { getPageQuery } from '@/utils/utils';
import { setAuthority } from '@/utils/authority';
import { reloadAuthorized } from '@/utils/Authorized';
import { fakeAccountLogin, getFakeCaptcha } from '@/services/user';
import Cookies from 'js-cookie';
export default {
  namespace: 'login',

  state: {
    status: 200,
    authData: null,
  },

  effects: {
    *login({ payload }, { call, put }) {

      //console.log(JSON.stringify(payload))
      const {data,code,msg} = yield call(fakeAccountLogin, payload);

      //console.log('response' + JSON.stringify(data))

      yield put({
        type: 'changeLoginStatus',
        payload: {
         authData:data,
         status:code
        }
      });


      // Login successfully
      if (code == 200) {
        //保存用户信息
        Cookies.set('loginUser',payload.userName);
        //cookie.save('loginUser', payload);
        //console.log('******88888888')
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        //yield put({ type: 'saveUser', payload})
        yield put(routerRedux.replace(redirect || '/'));
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          authData: 'guest',
        },
      });
      reloadAuthorized();
      // redirect
      sessionStorage.removeItem('loginUser')
      if (window.location.pathname !== '/user/login') {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            // search: stringify({
            //   redirect: window.location.href,
            // }),
          })
        );
      }
    },

  },

  reducers: {
    changeLoginStatus(state, { payload: {authData,status}}) {
      // console.log('authData' + JSON.stringify(authData))
      // console.log('msg'+message)
      setAuthority(authData);
      return {
        ...state,
        authData,
        status
      };
    },
    // saveUser(state,{payload:loginUser}){
    //   console.log('loginUser'+JSON.stringify(loginUser))
    //   return {...state,loginUser}
    // }
  },
};
